/**
 * 基于类对象且具有最小同步粒度的线程同步例程
 */
package thread;

public class J_BlockGranularity extends Thread {
    public static int m_data = 0;
    public static int m_times = 1000;
    public int m_ID;
    public boolean m_done;

    J_BlockGranularity(int id) {
        m_ID = id;
    }

    @Override
    public void run() {
        m_done = false;
        int d = ((m_ID % 2 == 0) ? 1 : -1);
        System.out.println("运行线程：" + m_ID + " 增量为：" + d);
        for (int i = 0; i < m_times; i++) {
            for (int j = 0; j < m_times; j++) {
                synchronized (J_BlockGranularity.class) {
                    m_data += d;
                }
            }
        }
        m_done = true;
        System.out.println("结束线程：" + m_ID);
    }

    public static void main(String args[]) {
        J_BlockGranularity t1 = new J_BlockGranularity(1);
        J_BlockGranularity t2 = new J_BlockGranularity(2);
        t1.m_done = false;
        t2.m_done = false;
        t1.start();
        t2.start();
        while (!t1.m_done || !t2.m_done) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("main 结果：m_data=" + m_data);
    }
}
